﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;
using Soveryn.Commerce.BaseClasses;
using Soveryn.Commerce.Shared;

namespace Soveryn.Commerce.Controls
{
    public partial class CartControl : ControlBaseClass
    {

        //public DataTable lines;
        public Boolean finalCartMode = false;
        public Boolean miniCartMode = false;
        public String moneyFormat = "C";
        public CartProperties cartProperties = new CartProperties();

        protected void Page_Load(object sender, EventArgs e)
        {

            if (IsPostBack)
                return;

            finalCartModeHiddenField.Value = finalCartMode.ToString();
            miniCartModeHiddenField.Value = miniCartMode.ToString();

            if (ParentPage.Website.IsDebugMode == true)
            {
                DebugInfoLiteral.Visible = true;
                moneyFormat = "C4";
            }

            //show/hide info based on if on checkout page (finalcartmode) 
            if (finalCartMode)
            {
                UpdateCheckoutButtonsLower.Visible = false;
                UpdateCheckoutButtonsUpper.Visible = false;
                TopPanel.Visible = false;
                BillShipInfoPanel.Visible = true;
                ShippingRow.Visible = true;
                SalesTaxRow.Visible = true;
                CountrySurchargeRow.Visible = true;
                ShippingMethodPanel.Visible = true;

                //Populate "Billing Address" section.
                BillingAddressDisplay.NicknameVisible = false;
                BillingAddressDisplay.PhoneVisible = false;
                BillingAddressDisplay.PhoneSecondaryVisible = false;
                BillingAddressDisplay.Address = ParentPage.Customer.BillingAddress;


                //Populate "Shipping Address" section.
                ShippingAddressDisplay.NicknameVisible = false;
                ShippingAddressDisplay.PhoneVisible = false;
                ShippingAddressDisplay.PhoneSecondaryVisible = false;
                ShippingAddressDisplay.Address = ParentPage.Customer.ShippingAddress;
                

            }
            else
            {
                CheckForUnpaidOrders();
            }

            if (miniCartMode)
            {
                CheckoutButton.OnClientClick = "top.location='/OrderCheckoutPROC.aspx';return false;";
                CheckoutButton2.OnClientClick = CheckoutButton.OnClientClick;
            }

            LoadCart();
        }

        private void CheckForUnpaidOrders()
        {

            DataSet orderDS = null;
            Dictionary<string, object> args = new Dictionary<string, object>();
            args.Add("WebsiteAPIKey", PageBaseClass.WebsiteAPIKey);
            args.Add("CustomerCartSessionID", ParentPage.CustomerCartSessionID);
            APIEnvelope env = Soveryn.Commerce.Shared.API.Call(PageBaseClass.CustomerAPIURL, "OrdersListForCustomer", args, false, false);
            if (env.response != null)
            {
                string response = (string)env.response;
                orderDS = new DataSet();
                orderDS.ReadXml(new StringReader((string)env.response));
            }

            if (DataUtils.HasRecords(orderDS, 0))
            {

                DataTable orderDT = orderDS.Tables[0];
                DataTable paymentsDT = orderDS.Tables[1];
                DataTable orderLinesDT = orderDS.Tables[2];

                int unpaidOrders = 0;
                foreach (DataRow orderRow in orderDT.Rows)
                {

                    OrderProperties order = OrderProperties.Create(orderRow);

                    if (order.AmountToPay != 0 && DateTime.UtcNow.Subtract(order.OrderCreateDate.Value).TotalMinutes <= 60 )
                    {
                        PayForOrderHyperLink.Text = "Goto order";
                        PayForOrderHyperLink.NavigateUrl = "/OrderCheckOut.aspx?OrderID=" + order.OrderID;
                        UnpaidOrdersPanel.Visible = true;
                        unpaidOrders++;
                    }

                }

                if (unpaidOrders > 1)
                {
                    PayForOrderHyperLink.Text = "Goto orders";
                    PayForOrderHyperLink.NavigateUrl = "/CustomerAccount.aspx";
                }

            }

        }

        public void LoadCart()
        {


            DataSet cartDS = Soveryn.Commerce.Shared.API.CallForDataSet(PageBaseClass.CustomerAPIURL, "CartDetail", new
            {
                WebsiteAPIKey = PageBaseClass.WebsiteAPIKey,
                CustomerCartSessionID = ParentPage.CustomerCartSessionID
            }, false, false);


            if (cartDS != null && DataUtils.HasRecords(cartDS, 0) && DataUtils.HasRecords(cartDS, 1))
            {

                cartProperties = CartProperties.Create(cartDS.Tables[0].Rows[0]);
                DataTable lines = cartDS.Tables[1];

                CartPanel.Visible = true;
                EmptyCartPanel.Visible = false;

                if (!String.IsNullOrEmpty(cartProperties.DiscountCode))
                {
                    ApplyDiscountPanel.Visible = false;
                    RemoveDiscountPanel.Visible = true;
                    DiscountCodeLabel.Text = cartProperties.DiscountCode;

                    
                    //ItemDiscountFromDiscountCode(string WebsiteAPIKey, string CustomerCartSessionID, string DiscountCode)


                }

                CartLineRepeater.DataSource = lines;
                CartLineRepeater.DataBind();

                //set cart line count cookie
                HttpCookie CustomerCartLineCountCookie = new HttpCookie("CustomerCartLineCount");
                CustomerCartLineCountCookie.Value = lines.Rows.Count.ToString();
                CustomerCartLineCountCookie.Expires = DateTime.Now.AddMonths(1);
                Response.Cookies.Add(CustomerCartLineCountCookie);

                SubTotalLabel.Text = cartProperties.SubTotal.Value.ToString(moneyFormat);
                ShippingLabel.Text = cartProperties.ShippingChargeAmount.Value.ToString(moneyFormat);
                CountrySurchargeLabel.Text = cartProperties.CountrySurchargeAmount.Value.ToString(moneyFormat);
                SalesTaxLabel.Text = cartProperties.TaxTotal.Value.ToString(moneyFormat);
                TotalLabel.Text = cartProperties.GrandTotal.Value.ToString(moneyFormat);

                //debug info
                if (ParentPage.Website.IsDebugMode.Value)
                {
                    DebugInfoLiteral.Visible = true;
                    DebugInfoLiteral.Text = "";
                    DebugInfoLiteral.Text += "<br />WeightTotal: " + cartProperties.WeightTotal.Value.ToString();
                    DebugInfoLiteral.Text += "<br />SubTotal: " + cartProperties.SubTotal.Value.ToString(moneyFormat);
                    DebugInfoLiteral.Text += "<br /><br /> ShipMethDisplayName: " + cartProperties.ShipMethDisplayName.ToString();
                    DebugInfoLiteral.Text += "<br /> SovShipMethodIDCode: " + cartProperties.SovShipMethodIDCode.ToString();
                    DebugInfoLiteral.Text += "<br />ShippingCharge: " + cartProperties.ShippingChargeAmount.Value.ToString(moneyFormat);
                    DebugInfoLiteral.Text += "<br /><br /> TaxSUBTotal: " + cartProperties.TaxSubTotal.Value.ToString(moneyFormat);
                    DebugInfoLiteral.Text += "<br /> ShippingTaxAmount: " + cartProperties.ShippingTaxAmount.Value.ToString(moneyFormat);
                    DebugInfoLiteral.Text += "<br /> ShippingTaxRateHistory: " + cartProperties.ShippingTaxRateHistory.Value.ToString();
                    DebugInfoLiteral.Text += "<br /> SalesTaxTotal: " + cartProperties.TaxTotal.Value.ToString(moneyFormat);
                    DebugInfoLiteral.Text += "<br /> CountrySurcharge: " + cartProperties.CountrySurchargeAmount.Value.ToString(moneyFormat);
                    DebugInfoLiteral.Text += "<br /> CountrySurchargeRateHistory: " + cartProperties.CountrySurchargeRateHistory.Value.ToString();
                    DebugInfoLiteral.Text += "<br /><br /> GrandTotal: " + cartProperties.GrandTotal.Value.ToString(moneyFormat);
                    DebugInfoLiteral.Text += "<br /> CartCreateDate: " + cartProperties.CartCreateDate.Value.ToString();
                    DebugInfoLiteral.Text += "<br /> CustomerCartSessionID: " + cartProperties.CustomerCartSessionID.ToString();
                    if (ParentPage.Customer != null)
                    {
                        DebugInfoLiteral.Text += "<br /> IsCreditApproved: " + ParentPage.Customer.IsCreditApproved.Value.ToString();
                        DebugInfoLiteral.Text += "<br /> Inactive: " + ParentPage.Customer.IsInactive.ToString();
                        DebugInfoLiteral.Text += "<br /> TaxExempt: " + ParentPage.Customer.IsStateProvJurisTaxExempt.ToString();
                        DebugInfoLiteral.Text += "<br /> UserName/Email: " + ParentPage.Customer.UserNameEmail.ToString();
                    }
                }

                SelectedSovShipMethodIDCodeHiddenField.Value = cartProperties.SovShipMethodIDCode;

                if ((cartProperties.SubTotal.HasValue || cartProperties.WeightTotal.HasValue) && finalCartMode == true)
                    FillShippingMethodSelector(cartProperties.SubTotal.Value, cartProperties.WeightTotal.Value, cartProperties.QuantityTotal.Value);

                return;

            }
            CartPanel.Visible = false;
            EmptyCartPanel.Visible = true;


        }

        protected void CartLineRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DataRowView drv = (DataRowView)e.Item.DataItem;
            DataRow row = drv.Row;

            HtmlTableRow CartLineTR = (HtmlTableRow)(e.Item.FindControl("CartLineTR"));
            HiddenField CartLineIDHiddenField = (HiddenField)(e.Item.FindControl("CartLineIDHiddenField"));
            Image CartLineImage = (Image)(e.Item.FindControl("CartLineImage"));
            HyperLink CartLineNameHyperLink = (HyperLink)(e.Item.FindControl("CartLineNameHyperLink"));
            HyperLink CartLineImageHyperLink = (HyperLink)(e.Item.FindControl("CartLineImageHyperLink"));
            Label CartLineTotalLabel = (Label)(e.Item.FindControl("CartLineTotalLabel"));
            Label CartLinePriceLabel = (Label)(e.Item.FindControl("CartLinePriceLabel"));
            Label CartLineSurchargeLabel = (Label)(e.Item.FindControl("CartLineSurchargeLabel"));
            TextBox CartLineQuantityTextBox = (TextBox)(e.Item.FindControl("CartLineQuantityTextBox"));
            Label CartLineQuantityLabel = (Label)(e.Item.FindControl("CartLineQuantityLabel"));
            Label CartLineRetailerDiscountLabel = (Label)(e.Item.FindControl("CartLineRetailerDiscountLabel"));
            Label CartLineManufacturerDiscountLabel = (Label)(e.Item.FindControl("CartLineManufacturerDiscountLabel"));
            LinkButton CartLineDeleteLinkButton = (LinkButton)(e.Item.FindControl("CartLineDeleteLinkButton"));
            Literal PropertiesLiteral = (Literal)(e.Item.FindControl("PropertiesLiteral"));

            //if any of these value > 0, then display values.
            decimal LineDiscountRateHistory = DataUtils.GetDecimal(row, "LineDiscountRateHistory");
            decimal CartLineManufacturerDiscount = DataUtils.GetDecimal(row, "LineMfgDiscountAmount");
            decimal CartLineRetailerDiscount = DataUtils.GetDecimal(row, "LineRetailerDiscountAmount");
            decimal CartLineSurcharge = DataUtils.GetDecimal(row, "PropertySurchargeTotal");
            if (CartLineManufacturerDiscount > 0) CartLineManufacturerDiscountLabel.Visible = true;
            if (CartLineRetailerDiscount > 0) CartLineRetailerDiscountLabel.Visible = true;

            if (CartLineSurcharge > 0)
            {

                XmlDocument xd = new XmlDocument();
                xd.LoadXml(DataUtils.GetStr(row, "PropertyXML"));

                XmlNodeList children = xd.FirstChild.SelectNodes("SKUProperty");

                PropertiesLiteral.Text = "<div class='properties'>";
                foreach (XmlNode childNode in children)
                {
                    String PropertyName = childNode.SelectSingleNode("PropertyName").InnerText;
                    String PropertyValue = childNode.SelectSingleNode("PropertyValue").InnerText;
                    Double Surcharge = Convert.ToDouble(childNode.SelectSingleNode("Surcharge").InnerText);
                    PropertiesLiteral.Text += "<div class='property'><span class='name'>" + PropertyName + "</span><span class='name'>(" + PropertyValue + ")</span>&nbsp;<span class='price'>+" + Surcharge.ToString(moneyFormat) + "</span></div>";
                }
                PropertiesLiteral.Text += "</div>";
                CartLineSurchargeLabel.Visible = true;
                CartLineSurchargeLabel.Text = "Surcharge +" + CartLineSurcharge.ToString(moneyFormat);
            }

            ItemProperties item = ItemProperties.Create(row);

            //Discount* - manufacturer rebate. Taxes are charged on original price. 
            CartLineManufacturerDiscountLabel.Text = "Discount* -" + CartLineManufacturerDiscount.ToString(moneyFormat);
            CartLineRetailerDiscountLabel.Text = "Discount -" + CartLineRetailerDiscount.ToString(moneyFormat);

            if (String.IsNullOrEmpty(item.ItemImageFile))
                item.ItemImageFile = "lostImage.jpg";

            CartLineImage.ImageUrl = "/ProductImagesCache/small-" + item.ItemImageFile;
            CartLineNameHyperLink.Text = item.ItemName + " - " + DataUtils.GetStr(row, "SKUName") + " (" + DataUtils.GetStr(row, "SKU") + ")";
            CartLineNameHyperLink.NavigateUrl = item.SEO.GetURL(ParentPage);
            CartLineImageHyperLink.NavigateUrl = CartLineNameHyperLink.NavigateUrl;
            CartLineTotalLabel.Text = DataUtils.GetDecimal(row, "LineTotal").ToString(moneyFormat);
            CartLinePriceLabel.Text = DataUtils.GetDecimal(row, "UnitPrice").ToString(moneyFormat);

            CartLineQuantityTextBox.Text = DataUtils.GetInt(row, "Quantity", 0).ToString();
            CartLineQuantityLabel.Text = CartLineQuantityTextBox.Text;
            CartLineIDHiddenField.Value = DataUtils.GetStr(row, "CartLineID");



            //debug info
            if (ParentPage.Website.IsDebugMode == true)
            {
                Literal LineDebugInfoLiteral = (Literal)(e.Item.FindControl("LineDebugInfoLiteral"));
                moneyFormat = "C4";
                LineDebugInfoLiteral.Visible = true;
                LineDebugInfoLiteral.Text = "";
                LineDebugInfoLiteral.Text += "<br />LineTaxableAmount: " + DataUtils.GetDecimal(row, "LineTaxableAmount").ToString(moneyFormat);
                LineDebugInfoLiteral.Text += "<br />LineStateProvJurisTaxAmount: " + DataUtils.GetDecimal(row, "StateProvJurisTaxAmount").ToString(moneyFormat);
                LineDebugInfoLiteral.Text += "<br />StateProvJurisTaxRateHistory: " + DataUtils.GetDecimal(row, "StateProvJurisTaxRateHistory").ToString();
                LineDebugInfoLiteral.Text += "<br />SKUWeight " + DataUtils.GetDecimal(row, "Weight").ToString();
                LineDebugInfoLiteral.Text += "<br />LineWeightTotal: " + DataUtils.GetDecimal(row, "LineWeightTotal", 0).ToString();
                LineDebugInfoLiteral.Text += "<br />LineDiscountRateHistory: " + LineDiscountRateHistory.ToString(moneyFormat);
                LineDebugInfoLiteral.Text += "<br />LineManufacturerDiscount: " + CartLineManufacturerDiscount.ToString(moneyFormat);
                LineDebugInfoLiteral.Text += "<br />LineRetailerDiscount: " + CartLineRetailerDiscount.ToString(moneyFormat);
                LineDebugInfoLiteral.Text += "<br />LineSurcharge: " + CartLineSurcharge.ToString(moneyFormat);
                LineDebugInfoLiteral.Text += "<br />LinePropertyXML: " + Server.HtmlEncode(DataUtils.GetStr(row, "PropertyXML"));
                LineDebugInfoLiteral.Text += "<br />LineCouponCode: " + DataUtils.GetStr(row, "LineCouponCode");
                LineDebugInfoLiteral.Text += "<hr />";

            }


            if (Convert.ToBoolean(miniCartModeHiddenField.Value))
            {

                CartLineNameHyperLink.NavigateUrl = "javascript:top.location='" + CartLineNameHyperLink.NavigateUrl + "'";
                CartLineImageHyperLink.NavigateUrl = CartLineNameHyperLink.NavigateUrl;

            }

            if (Convert.ToBoolean(finalCartModeHiddenField.Value))
            {
                CartLineDeleteLinkButton.Visible = false;
                CartLineQuantityLabel.Visible = true;
                CartLineQuantityTextBox.Visible = false;
            }

        }

        protected void UpdateButton_Click(object sender, EventArgs e)
        {

            foreach (RepeaterItem item in CartLineRepeater.Items)
            {

                HiddenField CartLineIDHiddenField = (HiddenField)(item.FindControl("CartLineIDHiddenField"));
                TextBox CartLineQuantityTextBox = (TextBox)(item.FindControl("CartLineQuantityTextBox"));

                Soveryn.Commerce.Shared.API.Call(PageBaseClass.CustomerAPIURL, "CartLineUpdateQuantity", new
                {
                    WebsiteAPIKey = PageBaseClass.WebsiteAPIKey,
                    CustomerCartSessionID = ParentPage.CustomerCartSessionID,
                    CartLineID = CartLineIDHiddenField.Value,
                    Quantity = Convert.ToInt32(CartLineQuantityTextBox.Text)
                }, false, false);

            }

            LoadCart();

        }

        protected void CartLineDeleteLinkButton_Click(object sender, EventArgs e)
        {

            LinkButton button = (LinkButton)sender;
            HiddenField CartLineIDHiddenField = (HiddenField)(button.Parent.FindControl("CartLineIDHiddenField"));

            Soveryn.Commerce.Shared.API.Call(PageBaseClass.CustomerAPIURL, "CartLineUpdateQuantity", new
            {
                WebsiteAPIKey = PageBaseClass.WebsiteAPIKey,
                CustomerCartSessionID = ParentPage.CustomerCartSessionID,
                CartLineID = CartLineIDHiddenField.Value,
                Quantity = 0
            }, false, false);


            LoadCart();

        }

        //**********************************Shipping Method Selection area ********************************
        //**********************************Shipping Method Selection area ********************************
        //**********************************Shipping Method Selection area ********************************

        protected void FillShippingMethodSelector(decimal cartSubtotal, decimal cartWeight, decimal cartQuantity)
        {

            if (cartWeight > 0)
            {

                DataSet ShipMethodDS = Soveryn.Commerce.Shared.API.CallForDataSet(PageBaseClass.CustomerAPIURL, "GetShippingMethods", new
                {
                    WebsiteAPIKey = PageBaseClass.WebsiteAPIKey,
                    TotalCostOfAllSKUs = cartSubtotal,
                    TotalWeightOfAllSKUs = cartWeight,
                    TotalQuantityOfAllSKUs = cartQuantity,
                    ShipPostalCode = ParentPage.Customer.ShippingAddress.AddressPostalCode,
                    ShipStateProvIDPostalAbrev = ParentPage.Customer.ShippingAddress.AddressStateProvIDPostalAbrev,
                    ShipCity = ParentPage.Customer.ShippingAddress.AddressCity,
                    ShipCountryIDPostalAbrev = ParentPage.Customer.ShippingAddress.AddressCountryIDPostalAbrev
                }, false, false);

                if (DataUtils.HasRecords(ShipMethodDS, 0))
                {
                    ShippingMethodRepeater.DataSource = ShipMethodDS.Tables[0];
                    ShippingMethodRepeater.DataBind();


                    if (String.IsNullOrEmpty(cartProperties.SovShipMethodIDCode))
                        SelectLowestShippingMethod();

                }

            }

        }

        private void SelectLowestShippingMethod()
        {

            decimal lowestShippingRate = -1;
            String SovShipMethodIDCode = "";
            String ShipMethodDisplay = "";
            HtmlTableRow LowestShippingMethodTR = null;
            foreach (RepeaterItem ri in ShippingMethodRepeater.Items)
            {

                HiddenField SovShipMethodIDCodeHiddenField = (HiddenField)(ri.FindControl("SovShipMethodIDCodeHiddenField"));
                HtmlTableRow ShippingMethodTR = (HtmlTableRow)(ri.FindControl("ShippingMethodTR"));
                HiddenField ShipMethodCalcAmountHiddenField = (HiddenField)(ri.FindControl("ShipMethodCalcAmountHiddenField"));
                Label ShipMethodDisplayLabel = (Label)(ri.FindControl("ShipMethodDisplayLabel"));

                Decimal shipMethodCalcAmount = Convert.ToDecimal(ShipMethodCalcAmountHiddenField.Value);

                if (lowestShippingRate == -1)
                {
                    lowestShippingRate = shipMethodCalcAmount;
                    SovShipMethodIDCode = SovShipMethodIDCodeHiddenField.Value;
                    ShipMethodDisplay = ShipMethodDisplayLabel.Text;
                    LowestShippingMethodTR = ShippingMethodTR;
                }
                else if (shipMethodCalcAmount < lowestShippingRate)
                {
                    lowestShippingRate = shipMethodCalcAmount;
                    SovShipMethodIDCode = SovShipMethodIDCodeHiddenField.Value;
                    ShipMethodDisplay = ShipMethodDisplayLabel.Text;
                    LowestShippingMethodTR = ShippingMethodTR;
                }
            }

            if (lowestShippingRate > -1)
            {
                SelectShippingMethod(SovShipMethodIDCode, lowestShippingRate, ShipMethodDisplay);
                LowestShippingMethodTR.Attributes["class"] = "shippingMethodSelected";
            }

        }

        protected void SelectShippingMethodButton_Click(Object sender, EventArgs e)
        {

            LinkButton btn = (LinkButton)sender;

            HiddenField SovShipMethodIDCodeHiddenField = (HiddenField)(btn.Parent.FindControl("SovShipMethodIDCodeHiddenField"));
            HtmlTableRow ShippingMethodTR = (HtmlTableRow)(btn.Parent.FindControl("ShippingMethodTR"));
            HiddenField ShipMethodCalcAmountHiddenField = (HiddenField)(btn.Parent.FindControl("ShipMethodCalcAmountHiddenField"));
            Label ShipMethodDisplayLabel = (Label)(btn.Parent.FindControl("ShipMethodDisplayLabel"));

            //select shipping method
            SelectShippingMethod(SovShipMethodIDCodeHiddenField.Value, Math.Abs(Convert.ToDecimal(ShipMethodCalcAmountHiddenField.Value)), ShipMethodDisplayLabel.Text);

            //set selected style
            ShippingMethodTR.Attributes["class"] = "shippingMethodSelected";

        }

        private void SelectShippingMethod(String SovShipMethodIDCode, Decimal ShipMethodCalcAmount, String ShipMethodDisplay)
        {

            //clear selected styles
            foreach (RepeaterItem ri in ShippingMethodRepeater.Items)
            {

                HtmlTableRow shippingMethodTR = (HtmlTableRow)(ri.FindControl("ShippingMethodTR"));
                shippingMethodTR.Attributes["class"] = "";

            }

            //Update the Shipping Method and Charges pertaining to the user's Cart.
            Dictionary<string, object> args = new Dictionary<string, object>();
            args.Add("WebsiteAPIKey", PageBaseClass.WebsiteAPIKey);
            args.Add("CustomerCartSessionID", ParentPage.CustomerCartSessionID);
            args.Add("ShipFreightCharge", ShipMethodCalcAmount);
            args.Add("SovShipMethodIDCode", SovShipMethodIDCode);
            args.Add("ShipMethDisplayName", ShipMethodDisplay);
            APIEnvelope env = Soveryn.Commerce.Shared.API.Call(PageBaseClass.CustomerAPIURL, "CartShippingUpdate", args, false, false);

            args = new Dictionary<string, object>();
            args.Add("WebsiteAPIKey", PageBaseClass.WebsiteAPIKey);
            args.Add("CustomerCartSessionID", ParentPage.CustomerCartSessionID);
            args.Add("SHIP_stateProvIDPostalAbrev", ParentPage.Customer.ShippingAddress.AddressStateProvIDPostalAbrev);
            args.Add("SHIP_countryIDPostalAbrev", ParentPage.Customer.ShippingAddress.AddressCountryIDPostalAbrev);
            args.Add("SHIP_postalCode", ParentPage.Customer.ShippingAddress.AddressPostalCode);
            env = Soveryn.Commerce.Shared.API.Call(PageBaseClass.CustomerAPIURL, "CartSetTaxesFinal", args, false, false);

            LoadCart();

        }

        protected void ShippingMethodRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DataRowView drv = (DataRowView)e.Item.DataItem;
            DataRow row = drv.Row;

            HiddenField SovShipMethodIDCodeHiddenField = (HiddenField)(e.Item.FindControl("SovShipMethodIDCodeHiddenField"));
            HiddenField ShipMethodCalcAmountHiddenField = (HiddenField)(e.Item.FindControl("ShipMethodCalcAmountHiddenField"));
            Label ShipMethodDisplayLabel = (Label)(e.Item.FindControl("ShipMethodDisplayLabel"));
            Label ShipMethodCalcAmountLabel = (Label)(e.Item.FindControl("ShipMethodCalcAmountLabel"));
            HtmlTableRow ShippingMethodTR = (HtmlTableRow)(e.Item.FindControl("ShippingMethodTR"));

            SovShipMethodIDCodeHiddenField.Value = row["SovShipMethodIDCode"].ToString();
            ShipMethodDisplayLabel.Text = row["ShipMethDisplayName"].ToString();
            ShipMethodCalcAmountHiddenField.Value = row["ShipMethodCalcAmount"].ToString();
            ShipMethodCalcAmountLabel.Text = Convert.ToDecimal(row["ShipMethodCalcAmount"]).ToString("C");

            if (cartProperties.SovShipMethodIDCode == SovShipMethodIDCodeHiddenField.Value)
                ShippingMethodTR.Attributes["class"] = "shippingMethodSelected";

        }

        protected void ApplyDiscountLinkButton_Click(object sender, EventArgs e)
        {

            Soveryn.Commerce.Shared.API.Call(PageBaseClass.CustomerAPIURL, "CartSetDiscounts", new
            {
                WebsiteAPIKey = PageBaseClass.WebsiteAPIKey,
                CustomerCartSessionID = ParentPage.CustomerCartSessionID,
                DiscountCode = DiscountCodeTextBox.Text
            },
                false,
                false);

            ParentPage.Reload();

        }

        protected void RemoveDiscountLinkButton_Click(object sender, EventArgs e)
        {

            Soveryn.Commerce.Shared.API.Call(PageBaseClass.CustomerAPIURL, "CartClearDiscounts", new
            {
                WebsiteAPIKey = PageBaseClass.WebsiteAPIKey,
                CustomerCartSessionID = ParentPage.CustomerCartSessionID
            },
                false,
                false);

            ParentPage.Reload();


        }

    }
}